package ChainOfResponsibility;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.Ordered;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * @author ling007
 * @date 2024/5/24 10:16
 * @desciption: 责任链上下文容器
 */
public final class OrderCreateChainContext<T> implements CommandLineRunner {

    private final List<OrderCreateChainHandler> orderCreateChainHandlerContainer = new ArrayList();

    public void handler(T requestParam){
        // 此处根据 Ordered 实际值进行排序处理
        orderCreateChainHandlerContainer.stream()
                .sorted(Comparator.comparing(Ordered::getOrder)).forEach(each -> each.handler(requestParam));
    }

    @Override
    public void run(String... args) throws Exception {
        // 通过 Spring 上下文容器，获取所有 CreateOrderChainContext Bean
        Map<String, OrderCreateChainHandler> chainFilterMap = ApplicationContextHolder.getBeansOfType(OrderCreateChainHandler.class);
        // 将对应 Bean 放入责任链上下文容器中
        chainFilterMap.forEach((beanName, bean) -> orderCreateChainHandlerContainer.add(bean));
    }
}
